﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Code.Models;
using Code.BLL;
using QianBuo.Lottery.Web.Areas.Manage.Models.Authorization;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    public class AuthorizationController : BaseController
    {
        [Authorize(Roles = "Manager_Site_Authority")]
        public ActionResult Index()
        {
            string[] t = new string[] { AuthorityKey.Manager_Site_Authority.ToString(), AuthorityKey.Manager.ToString() };
            var model = new IndexModel();
            model.Authoritys = CacheManage.Authority
                .Where(p => !t.Contains(p.Value.AuthorityKey))
                .Select(p => new AuthorityItem
                {
                    ID = p.Key,
                    State = p.Value.State == (short)AuthorityState.Enable,
                    Name = p.Value.Name,
                    Remark = p.Value.Remark
                }).ToArray();

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Authority")]
        public ActionResult Index(IndexModel model)
        {
            if (ModelState.IsValid)
            {
                var ups=model.Authoritys.ToNameValue(p => (object)new { State = (short)(p.State ? AuthorityState.Enable : AuthorityState.Disable) }, p => (object)new { p.ID });
                var AM = new AuthorizationManage();
                int rs = AM.Update(ups);
                string msg="保存失败,请稍后再试!".AlertOffPage();
                if (rs >= 0)
                {
                    msg = Url.Action("Index").Redirect("保存成功!");
                    CacheManage.IsLoadAuthority = true;
                    CacheManage.IsLoadAuthentication = true;
                }
                ViewData["msg"] = msg;
            }
            return View(model);
        }


        [Authorize(Roles = "Manager_Site_Authorization")]
        public ActionResult Role()
        {
            var model = new RoleModel();
            model.Roles = CacheManage.Roles.Select(p => new RoleItemModel { ID = p.Key, Name = p.Value.Name, State =(RoleState) p.Value.State }).ToArray();
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_Authorization")]
        public ActionResult Edit(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Role");
            var item = CacheManage.Roles.Select(p => new RoleItemModel { ID = p.Key, Name = p.Value.Name, State =(RoleState )p.Value.State })
                .FirstOrDefault(p => p.ID == id);
            if (item == null)
                return RedirectToAction("Role");

            string[] t = new string[] { AuthorityKey.Manager.ToString() };
            var model = new EditModel { Role = item };

            model.Auths = new Web.Models.ModelNameValue<int, bool>(
                CacheManage.Authentication.Values.Where(p => p.RolesID == id).Select(p => new NameValueItem<int, bool> { Key = p.AuthorityID, Value = p.State == (short)AuthenticationState.Enable }));
            item.Authoritys = CacheManage.Authority.Where(p => !t.Contains(p.Value.AuthorityKey)).GroupJoin(model.Auths, p => p.Key, p => p.Key, (p1, p2) => new AuthorityItem
            {
                ID = p1.Key,
                Name = p1.Value.Name,
                Remark = p1.Value.Remark,
                State = p2.Select(p=>p.Value).FirstOrDefault()
            }).ToArray();
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Authorization")]
        public ActionResult Edit(EditModel model)
        {
            if (ModelState.IsValid)
            {
                var AM = new AuthorizationManage();
                var ups = model.Auths.Join(model.Role.Authoritys, p => p.Key, p => p.ID, (p1, p2) => new { p1, p2 })
                    .ToNameValue(p => (object)new { State = (short)(p.p2.State ? RoleState.Enable : RoleState.Disable) }, p => (object)new { AuthorityID=p.p2.ID, RolesID = model.Role.ID });
                var tp=model.Auths.Select(p=>p.Key).ToArray();
                var ins = model.Role.Authoritys.Where(p => !tp.Contains(p.ID)).Select(p => new { RolesID = model.Role.ID, AuthorityID = p.ID, State = (short)(p.State ? RoleState.Enable : RoleState.Disable) }).ToArray();
                AM.BeginTransaction();
                AM.Update<Authentication>(ups);
                AM.Insert<Authentication>(ins);
                AM.Update<Roles>(new { model.Role.Name, State = (short)model.Role.State }, new { model.Role.ID });
                int rs = AM.ExecuteTransaction(ups.Count + ins.Length + 1);
                string msg = "保存失败,请稍后再试!".AlertOffPage();
                if (rs >= 0)
                {
                    msg = Url.Action("Role").Redirect("保存成功!");
                    CacheManage.IsLoadAuthentication = true;
                    CacheManage.IsLoadRoles = true;
                }
                ViewData["msg"] = msg;
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_Authorization")]
        public ActionResult Add()
        {
            string[] t = new string[] { AuthorityKey.Manager.ToString() };
            var model = new EditModel()
            {
                Role = new RoleItemModel
                    {
                        State=RoleState.Enable,
                        Authoritys = CacheManage.Authority.Where(p => !t.Contains(p.Value.AuthorityKey))
                        .Select(p => new AuthorityItem
                        {
                            ID = p.Key,
                            State = p.Value.State == (short)AuthorityState.Enable,
                            Name = p.Value.Name,
                            Remark = p.Value.Remark
                        }).ToArray(),
                    },
                Auths=new Web.Models.ModelNameValue<int,bool>(),
            };
            return View("Edit",model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Authorization")]
        public ActionResult Add(EditModel model)
        {
            if (ModelState.IsValid)
            {
                var AM = new AuthorizationManage();
                var tp = model.Auths.Select(p => p.Key).ToArray();
                var ins = model.Role.Authoritys.Where(p => !tp.Contains(p.ID))
                    .Select(p => new { RolesID = new SqlExpression("@RoleID"), AuthorityID = p.ID, State = (short)(p.State ? RoleState.Enable : RoleState.Disable) }).ToList();
                ins.Add(new { RolesID = new SqlExpression("@RoleID"), AuthorityID = 1, State = (short)RoleState.Enable });
                AM.BeginTransaction();
                AM.Insert<Roles>(new { model.Role.Name, State = (short)model.Role.State});
                AM.Execute(new SqlExpression("declare @RoleID int set @RoleID=@@identity"));
                AM.Insert<Authentication>(ins.ToArray());
                int rs = AM.ExecuteTransaction(ins.Count+1);
                string msg = "保存失败,请稍后再试!".AlertOffPage();
                if (rs >= 0)
                {
                    msg = Url.Action("Role").Redirect("保存成功!");
                    CacheManage.IsLoadAuthentication = true;
                    CacheManage.IsLoadRoles = true;
                }
                ViewData["msg"] = msg;
            }
            return View("Edit",model);
        }
    }
}
